sugarfreeControllers.controller('RecordController',
	['$scope','$log','$http', '$filter', '$timeout', '$q','HttpService','ngTableParams', 'Utils', '$interval', 'AUTH_EVENTS','TimeService','DictionarySerivce', 'WebsocketService',
	  function ($scope,$log,$http,$filter, $timeout, $q,httpService, ngTableParams, Utils, $interval, AUTH_EVENTS,timeService,dicSerivce, WebsocketService) {
  "use strict";
  
  $scope.retrieveBookedMombers = function(lessonId){retrieveBookedMombers(lessonId);};
  
  //beginDate format is yyyy-MM-dd
  $scope.retrieveRecords = function (beginTime,endTime) {
	  	  Utils.setProcessParclose(true);
	  	  var classType = dicSerivce.getClassTypes();
		  var _queryRecord 	= "lesson/query";
		  var _dataRecord 	= "?uid=" + $scope.uid + 
		  					  "&beginTime=" + beginTime +
		  					  "&endTime=" + endTime;
		  var _urlRecord = $scope.apiUrl + _queryRecord + _dataRecord;
		  console.log("retrieve records from:", _urlRecord);
		  $http.get(_urlRecord).success(function(data){
			  $scope.records = data;
			  if($scope.log.debug){
				  $log.info("retrieveRecords==>",$scope.records);
			  }
			  angular.forEach($scope.records,function(record){
				  switch (record.course.classType.value) {
					case 1:
						record.classTypeShortName = classType.class_diy.shortName;
						break;
					case 2:
						record.classTypeShortName = classType.class_group.shortName;
						break;
					case 3:
						record.classTypeShortName = classType.class_private.shortName;
						break;
				  }
				  
				  console.log("record.endTime",record.endTime);
				  var endDate =  new Date(record.endTime.substr(0, 4),
						  parseInt(record.endTime.substr(4, 2), 10) - 1,
						  record.endTime.substr(6, 2),
						  record.endTime.substr(8, 2),
						  record.endTime.substr(10, 2)
				  );
				  console.info("endDate",endDate);
				  //endDate.setTime(endDate.getTime() + (record.duration * 60 * 1000));
				  
				  
				  record.tBeginTime = record.beginTime.substr(8).substr(0,2) + ":" +record.beginTime.substr(8).substr(2);
				  record.tEndTime = timeService.parse(endDate,'HH:mm');
				  record.numberLimit = record.numberLimit > 100000?"不限":record.numberLimit+"人参加";
				  
				  //set lesson status
				  var lessonStatus = dicSerivce.getLessonStatus();
				  var beginDate =  new Date(record.beginTime.substr(0, 4),
						  parseInt(record.beginTime.substr(4, 2), 10) - 1,
						  record.beginTime.substr(6, 2),
						  record.beginTime.substr(8, 2),
						  record.beginTime.substr(10, 2)
				  );
				  var date = new Date();
				  var beginDateTime = beginDate.getTime();
				  var nowDateTime = date.getTime();
				  var threeH = 3600*1000*3;//unit is 'ms'
				  //alert(beginDateTime);
				  if(record.status !== 16384){
					  record.cance = 0;
					  if(beginDateTime > (nowDateTime + threeH)){
						  record.lessonStatus= lessonStatus.open;
					  }else if(beginDateTime > nowDateTime && beginDateTime <= nowDateTime + threeH){
						  record.lessonStatus= lessonStatus.later;
					  }else if(beginDateTime <= nowDateTime && nowDateTime < endDate.getTime() ){
						  record.lessonStatus= lessonStatus.proceed;
					  }else{
						  record.lessonStatus= lessonStatus.outdated;
					  }
				  }else{
					  record.cance = 1;
					  record.lessonStatus= lessonStatus.closed;
				  }
				  
			  });
			  Utils.setProcessParclose(false);
			  //$log.log("$scope.records",$scope.records);
		  });
  };
  
  
  function retrieveBookedMombers(record){
  	  if(record.status===16384){
  	  	return ;
  	  }
  	  Utils.setParclose(true);
  	  Utils.setProcessParclose(true);
	  $scope.selectedRecord = record;
	  $scope.selectedRecord.lessonTime = timeService.patten($scope.selectedRecord.beginTime);
	  //根据lessonId获取上课的学员信息
	  $http.get("receipt/query?lessonId=" + record.id +"&status=5").then(function (resp){
		  $scope.receipts = resp.data;
		  if($scope.log.debug){
			  $log.info("$scope.receipts",$scope.receipts );
			  $log.info("$scope.selectedRecord",$scope.selectedRecord);
		  }
		  $scope.page.useOrderDetail = true;
		  Utils.setProcessParclose(false);
	  },function(){
		  alert("查询出错！！！");
		  Utils.setParclose(false);
		  Utils.setProcessParclose(false);
	  });
  }
  
  
  $scope.cancelBox = function(record,lessonId,status,beginTime,endTime){
	  if(status !== 0){
		  return ;
	  }
	  $scope.closeRecord = record;
	  Utils.setParclose(true);
	  $scope.lessonId = lessonId;
	  $scope.status = status;
	  $scope.beginTime = beginTime;
	  $scope.endTime = endTime;
	  $scope.cancelBoxFlag = true;
  };
  
  $scope.cancelLesson = function(lessonId,status,beginTime,endTime){
	  console.log("!$scope.reason",$scope.reason);
	  if(!$scope.reason){
		  $scope.cancelLessonReasonMessage = "请输入关课理由";
		  return ;
	  }else{
		  $scope.cancelLessonReasonMessage = "";
	  }
	  if(status===0){
		  var _cancelLesson = "lesson/cancel?id=" + lessonId;
		  var _dataStr = "&reason=" + $scope.reason;
		  var _urlRecord = $scope.apiUrl + _cancelLesson;
		  console.log("cancel lesson:", _urlRecord);
		$http ({
              method: 'POST',
              url: _urlRecord,
              data: _dataStr,
              headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        }).
          then(function(response) {
        	switch (response.data.errCode) {
				case "8000":
					alert("取消成功");
					break;
				case "8209":
					alert("取消失败，要关闭的课程不存在");
					break;
				case "8126":
					alert("取消失败，要关闭的课程已结束");
					break;
				case "8128":
					alert("取消失败，要关闭的课程即将开始，关闭课程操作需距开课前3小时进行");
					break;
			}
        	  $scope.reason = "";
	          $scope.retrieveRecords(beginTime,endTime);
			  $scope.cancelBoxFlag=!$scope.cancelBoxFlag;
			  Utils.setParclose(false);
          }, function(response){
        	  $scope.reason = "";
        	  Utils.setParclose(false);
              alert("关闭失败，请联系管理员！");
          });
		
	  }
  };
  //TODO: end

  function getIncome(){
    return $http.get("statistics/beans")
		.then(
  	   		function(response){
  	   			WebsocketService.setIncome(response.data);
  	   			$scope.income = WebsocketService.getIncome;
  	   			console.log($scope.income + "income promise");
  	   		}
		)	;
  }
  
  $scope.signForm = function(){
  	Utils.setParclose(true);
  	$scope.page.useSignForm = true;
  }
  
  $scope.closeSignForm = function(){
  	$scope.errMsg = $scope.errMsg || {};
  	$scope.errMsg.signMsg = '';
  	$scope.signCode = '';
  	$scope.page.useSignForm = false;
  	Utils.setParclose(false);
  }
  
  $scope.sign = function(){
  	$scope.errMsg = $scope.errMsg || {};
  	if(!$scope.signCode){
  		$scope.errMsg.signMsg = $scope.msg.emptySign;
  		return ;
  	}else{
  		$scope.errMsg.signMsg = "";
  	}
  	
  	var _url = "receipt/sign";
  	var _dataStr="code=" + $scope.signCode;
  	Utils.setTopParclose(true);
  	httpService.post(_url,_dataStr).then(
  		function(rsps){
  			console.info("rsps",rsps);
  			if(rsps.data.errCode === '8000'){
  				alert('签到成功');
  				$scope.signCode = '';
  				$scope.page.useSignForm = false;
	  			Utils.setTopParclose(false);
	  			Utils.setParclose(false);
  			}else{
  				Utils.setTopParclose(false);
  				$scope.errMsg.signMsg = $scope.msg.invalidSign;
  				//$scope.signCode = "";
  			}
  			
  		},
  		function(rsps){
  			alert('签到出现异常');
  			Utils.setTopParclose(false);
  			//Utils.setParclose(false);
  		}
  	);
  	
  }

  function initData(){
	  $scope.records = [];
	  $scope.week = generateWeekLabel();
	  getIncome();
	  $scope.receivedReceipts = WebsocketService.receipts;
	  ////////////////
	  
	  function generateWeekLabel(){
		  var dayOfWeeks = dicSerivce.getDayOfWeeks();
		  var weekLabel = [];
		  var daym = 3600 * 24 * 1000 ;
		  var suffix ="0000";
		  //delay chengwanliu
		  for(var i = 0 ; i < 7 ; i++){
			  var date = new Date();
			  var dateNext = new Date();
			  date.setTime(date.getTime() + daym*i);
			  dateNext.setTime(dateNext.getTime() + daym*(i+1));
			  var year = date.getFullYear();
			  var month = ""+(date.getMonth() + 1);
			  var day = ""+date.getDate();
			  var dayOfWeek = date.getDay() + 1;
			  var header_sub = "";
			  switch (i) {
				  case 0:
					  header_sub = "今天"; break;
				  case 1:
					  header_sub = "明天"; break;
				  case 2:
					  header_sub = "后天"; break;
					  
				  default:
					  header_sub = month+"月"+day+"日"; break;
			  }
			  var found = $filter('filter') (dayOfWeeks, {value: dayOfWeek}, true);
			  var nextYear = dateNext.getFullYear();
			  var nextMonth = ""+(dateNext.getMonth() + 1);
			  var nextDay = ""+dateNext.getDate();
			  var labelObj = {
					  header:header_sub + found[0].name,
					  week:found[0].name.value,
					  beginTime:year+ (month.length>1?month:"0"+month) + (day.length>1?day:"0"+day)+suffix,
					  endTime:nextYear + (nextMonth.length>1?nextMonth:"0"+nextMonth) + (nextDay.length>1?nextDay:"0"+nextDay)+suffix
			  };
			  weekLabel.push(labelObj);
		  }
		  return weekLabel;
	  }
	  
	  $scope.page = {
		useOrderDetail:false,
		useSignForm:false
	  };
	  
	  
	  $scope.msg={
			emptySign:"错误：签到码为空",
			invalidSign:"错误：无效的签到码"
	  };
	  
	  $scope.log={
		debug:true	  
	  };
  }
  
  initData();
}]);